package bud.mobile.controller;


import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import bud.mobile.service.IMobileMemberService;
import bud.mobile.service.IMobileMemberService.MemberResult;
import bud.vo.ChatDTO;
import bud.vo.MemberDTO;

@Controller
@Slf4j
public class ChatController {
	@Inject
	private IMobileMemberService service;
	public IMobileMemberService getService() {
		return service;
	}
	public void setService(IMobileMemberService service) {
		this.service = service;
	}
	
	@RequestMapping("chat/chatList")
	public String chatList(Model model, HttpServletRequest request){
		HttpSession session = request.getSession();
		MemberDTO member = (MemberDTO)session.getAttribute("memberSession");
		List<MemberDTO> friends = member.getFriendList();
		
		List<MemberDTO> chatFriendList = new ArrayList<MemberDTO>();
		List<ChatDTO> chatList = new ArrayList<ChatDTO>();
		
		ChatDTO chat = new ChatDTO();
		chat.setCh_sender(member.getMem_no());
		for (int i=0; i<friends.size(); i++){
			chat.setCh_receiver(friends.get(i).getMem_no());
			ChatDTO tempChat = service.getRecentChat(chat);
			if (tempChat != null){
				chatFriendList.add(friends.get(i));
				chatList.add(tempChat);
			}
		}
		model.addAttribute("chatFriendList", chatFriendList);
		model.addAttribute("chatList", chatList);
		
		return "chat/chatList";
	}
	
	@RequestMapping("chat/chatChatting")
	public String chatChatting(int mem_no, Model model, HttpServletRequest request){
		HttpSession session = request.getSession();
		MemberDTO memberSession = (MemberDTO)session.getAttribute("memberSession");
		
		ChatDTO chat = new ChatDTO();
		chat.setCh_sender(memberSession.getMem_no());
		chat.setCh_receiver(mem_no);
		List<ChatDTO> chatList = service.getChat(chat);
		model.addAttribute("chatList", chatList);
		
		MemberDTO friend = service.getMember(mem_no);
		model.addAttribute("friend", friend);
		
		return "chat/chatChatting";
	}

	@RequestMapping("chat/chatAdd")
	public String chatAdd(ChatDTO chat){
		service.insertChat(chat);
		return "jsonView";
	}
	
}
